Psychological variables and properties
I’ve noticed that there are two different ways developers locate private variables used by properties. One way is to locate the private variable next to the property that returns them and all other private variable located elsewhere.
#region Private fields
private string _Member;
private int _AnotherMember;
#endregion
#region Properties
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
private int _Age;
public int Age
{
get { return _Age; }
set { _Age = value; }
}
#endregion
The other way is to separate all private variables, both the ones that are used by properties and the ones used by the rest of the class, into two different locations.
#region Private fields
private string _Name;
private int _Age;
private string _Member;
private int _AnotherMember;
#endregion
#region Properties
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public int Age
{
get { return _Age; }
set { _Age = value; }
}
#endregion
There are problems and advantages with both approaches even though they appear minor. It has to do with the psychological difference between variables.
The psychological difference
Let’s say there are two different types of private variables – the ones used by properties and the ones not used by properties. Basically, there is no difference. A private variable is the same no matter how it is used, but the usage is what makes the difference.
A private variable used by a property is a sort of a placeholder that is only accessed through the property. Because of that, it only exists because of the property and can therefore be considered a part of the class’s interface.
A private variable that isn’t used by a property is used by multiple methods in a more interactive manor. It exists because the inner workings of the class needs it and it has nothing to do with the public interface.
The difference is psychological because a private variable is the same no matter how it is used. I don’t think there is a wrong way to do it and it all comes down to personal choice of the developer.
Personally, I use the first approach because I can’t ignore the psychological difference and thinks it makes my code more maintainable and easier to understand. I find it to be difficult to get an overview of a class that has all private variables grouped together, because they don’t tell me anything about how they are used. Then I need to find the references manually in the code and it just seems unnecessary in many cases.
Another thing is that I like to comment the different private variables, but only the ones that are not used by properties. The ones used by properties don't need to be commented because it is obvious what they do, but only if they are located next to their respective property.